﻿using System;
using System.Collections.Generic;
using System.Linq;
using Widgetsphere.Autos.Websitev2.Objects;
using Widgetsphere.Autos.API.FacetedNavigation;
using Widgetsphere.AutoAggregate.Website.Objects;
using HP.Datastore.Common;
using Widgetsphere.Autos.API;

namespace Widgetsphere.Autos.Websitev2
{
    public partial class auto_results : BasePage
    {
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            this.Populate();

            pnlStats.Visible = true;
        }

        private void Populate()
        {
            var query = new ListingQuery(this.Request.Url.AbsoluteUri);

            //Process ZIP
            if (!string.IsNullOrEmpty(query.Zip))
            {
                if (query.Radius > 0)
                {
                    var zipInfo = GeoHelper.GetGeoFromZip(query.Zip);
                    if (zipInfo != null)
                        query.FieldFilters.Add(new FieldFilterLocation() { Comparer = ComparisonConstants.LessThanOrEq, Latitude = (double)zipInfo.Latitude, Longitude = (double)zipInfo.Longitude, Radius = (double)query.Radius });
                }
            }

            if (query.FieldSorts.Count == 0)
                query.FieldSorts.Add(new FieldSortPostDate() { SortDirection = SortDirectionConstants.Desc });

            var results = ResultsCacheHelper.Query(query);

            this.DimensionListControl1.Populate(results, ConfigHelper.JobDimensionAlias);
            this.ListingGrid1.Populate(results);
            this.DimensionFilterDisplayControl1.Populate(results, query, RepositoryHelper.MasterResults, ConfigHelper.JobDimensionAlias, "/auto-results.aspx");

            var startIndex = ((results.Query.PageOffset - 1) * results.Query.RecordsPerPage) + 1;
            var endIndex = startIndex + results.Query.RecordsPerPage - 1;

            //SEO
            this.Page.Title = SEOHelper.GetSEOTitle(results);
            this.MetaTagDescription = SEOHelper.GetSEOTitle(results);
            this.MetaTagKeywords = SEOHelper.GetSEOTitle(results);

            MapControl1.Populate(results);

            //if (SessionHelper.ShowStats)
            //{
            //  var stats = new LiteralControl();
            //  stats.Text = "<div class=\"stats\">Compute time: " + (results.ComputeTime == -1 ? "[from cached]" : (results.ComputeTime).ToString("###,###,##0") + " ms") + "</div>";
            //  this.pnlStats.Controls.AddAt(0, stats);
            //}

        }

    }
}